package h0903;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
  * @description 前k个高频元素
  * @author 不知名帅哥
  * @date 2024/9/3 22:43
  * @version 1.0
*/
public class FirstKHighFrequencyElements {
    public static void main(String[] args) {
        int[] nums={1,1,1,2,2,3};
        int[] res = topKFrequent(nums, 2);
        System.out.println(Arrays.toString(res));
    }
    public static int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num,map.getOrDefault(num,0)+1);
        }
        List<Integer> res = map.keySet().stream().sorted((o1, o2) -> map.get(o2) - map.get(o1)).collect(Collectors.toList());
        int[] ans = new int[k];
        for (int i = 0; i < k; i++) {
            ans[i]=res.get(i);
        }
        return ans;
    }
}
